package com.sgb.kjwl.view.ui.fragment.self;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentEnterpriseRegistrationBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.SupplierAuthEntity;
import com.sgb.kjwl.utils.Constants;
import com.sgb.kjwl.view.event.CategoryEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.event.self.AuthenticationEvent;
import com.sgb.kjwl.view.ui.SinglePickBuilder;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegisterActivity3;
import com.swgk.core.util.DateUtils;
import com.sgb.link.view.widget.OneAndTwoLevelMultipleChoiceWindow;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.SimpleCountDownTimer;
import com.sgb.kjwl.viewmodel.self.RegisterModelE;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EnterpriseRegistrationFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EnterpriseRegistrationFragment extends AppFragment {

    private final int LICENS = 10;//营业执照
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private boolean isAgain;
    private List<String> listLicens;
    private List<String> typeList;
    private boolean isLong = false;
    //企业服务类型
    private List<PickFilterEntity<List<PickFilterEntity>>> comTypes = new ArrayList<>();
    private List<PickFilterEntity> comReallyTypes = new ArrayList<>();
    private int typePosition;
    @Inject
    RegisterModelE viewModel;
    RegisterActivity3 activity;
    FragmentEnterpriseRegistrationBinding binding;
    private boolean isCheckEnduring = false;
    private boolean isChecked = true;//同意阅读协议
    private int comTypePosition;
    public static final int RequestCodeE = 1;

    private OneAndTwoLevelMultipleChoiceWindow window;

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    SupplierAuthEntity entity;
    String companyId;

    public EnterpriseRegistrationFragment() {
        // Required empty public constructor
    }

    private String isStartTimer = "true";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof RegisterActivity3) {
            activity = (RegisterActivity3) context;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activity = null;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }


    public static EnterpriseRegistrationFragment newInstance(String param1, boolean param2, String companyId) {
        EnterpriseRegistrationFragment fragment = new EnterpriseRegistrationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putBoolean(ARG_PARAM2, param2);
        args.putString("companyId", companyId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            isAgain = getArguments().getBoolean(ARG_PARAM2);
            companyId = getArguments().getString("companyId");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_enterprise_registration, container, false);
        viewModel.supplierAuthEntity.get().setUserDTO(new SupplierAuthEntity.UserDTO());
        binding.setViewModel(viewModel);
        return binding.getRoot();

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }


    private void initView() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        listLicens = new ArrayList<>();
        binding.addImg.setOnClickListener(this);
        binding.comType.setOnClickListener(this);
        binding.comServiceType.setOnClickListener(this);
        binding.tvGetCodeBtn.setOnClickListener(this);
        binding.go.setOnClickListener(this);
        binding.comAddress.setOnClickListener(this);
        binding.tvAgreement.setOnClickListener(this);
        binding.tvCompany.setOnClickListener(this);
        binding.createTime.setOnClickListener(this);
        binding.tvChangqi.setOnClickListener(this);
        binding.businessTerm.setOnClickListener(this);
        binding.ivCheckedBox.setOnClickListener(this);

        binding.etCompany.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    binding.etCompany.setFocusableInTouchMode(true);
                    InputMethodManager inputManager = (InputMethodManager)binding.etCompany.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(binding.etCompany, 0);
                }else {
                    binding.etCompany.setVisibility(View.GONE);
                    binding.tvCompany.setVisibility(View.VISIBLE);
                    binding.tvCompany.setText(binding.etCompany.getText());
                }
            }
        });
        if ("1".equals(mParam1)) {
            binding.llCode.setVisibility(View.GONE);
            binding.llPwd.setVisibility(View.GONE);
//            isChecked = false;
            binding.tvSureBtn.setText("提交审核");
            binding.llAgreement.setVisibility(View.GONE);
            binding.llAgreement2.setVisibility(View.VISIBLE);
            binding.ivCheckBox.setOnClickListener(this);
            binding.tvAgreement2.setOnClickListener(this);
            binding.tvPrivacy.setOnClickListener(this);
            if (TextUtils.isEmpty(companyId)) {
                viewModel.person.get().setRealName(SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false) ? SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "") : "");
                viewModel.person.get().setIdentityCard(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ID_CARD, ""));
                binding.name.setEnabled(TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false) ? SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "") : ""));
                binding.idCode.setEnabled(TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ID_CARD, "")));
                viewModel.person.get().setTelPhone(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
                viewModel.person.get().setUsername(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
                viewModel.person.get().setUserNo(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
                binding.mobile.setEnabled(false);
                viewModel.supplierAuthEntity.get().setUserDTO(viewModel.person.get());
                binding.setViewModel(viewModel);
            }
        }
        if (binding.llAgreement.getVisibility() != View.GONE){
            binding.tvSureBtn.setEnabled(false);
        } else {
            binding.tvSureBtn.setEnabled(true);
            binding.tvSureBtn.setOnClickListener(this);
        }
        if (isAgain) {
            viewModel.companyAuthDetail(companyId);
        }


        setSureBtn(isChecked);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.create_time:
                showTimePop();
                break;
            case R.id.businessTerm:
                showTimePop3();
                break;
            case R.id.go:
                if (isAgain)
                    EventBus.getDefault().post(CategoryEvent.make(EventConstant.EVENT_RE_AUTH_COM, null));
                EventBus.getDefault().postSticky(AuthenticationEvent.make(EventConstant.EVENT_JOIN_COM, 0));
                activity.finish();
                break;
            case R.id.tv_changqi:
                if (isCheckEnduring) {
                    binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_no_select_item), null, null, null);
                    isCheckEnduring = false;
                } else {
                    isCheckEnduring = true;
                    binding.businessTerm.setText("");
                    binding.businessTerm.setHint("请选择营业执照有效期");
                    binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_select_checkbox_item), null, null, null);
                }
                break;
            case R.id.tv_sure_btn:
                if (!isChecked && "1".equals(mParam1)){
                    MToast.showToast(getActivity(), "请先阅读经营帮企业认证协议和隐私协议");
                    return;
                }
                if (TextUtils.isEmpty(binding.etCompany.getText())) {
                    MToast.showToast(getActivity(), "企业名称不能为空");
                    return;
//                } else if (!binding.etCompany.getText().toString().equals(entity.getCompanyName())) {
                } else {
                    viewModel.supplierAuthEntity.get().setCompanyName(binding.etCompany.getText().toString());
                }
                if (TextUtils.isEmpty(binding.comNo.getText())) {
                    MToast.showToast(getActivity(), "统一社会信用代码不能为空");
                    return;
//                } else if (!binding.comNo.getText().toString().equals(entity.getCreditCode())) {
                } else {
                    viewModel.supplierAuthEntity.get().setCreditCode(binding.comNo.getText().toString());
                }
                if (TextUtils.isEmpty(binding.comType.getText())) {
                    MToast.showToast(getActivity(), "企业类型不能为空");
                    return;
//                } else if (!binding.comType.getText().toString().equals(entity.getCompanyType())) {
                } else {
                    viewModel.supplierAuthEntity.get().setCompanyType(binding.comType.getText().toString());
                }
                if (TextUtils.isEmpty(binding.comServiceType.getText())) {
                    MToast.showToast(getActivity(), "主营业务不能为空");
                    return;
//                } else if (!binding.comServiceType.getText().toString().equals(entity.getServiceType())) {
                }
                viewModel.supplierAuthEntity.get().setMainBusiness(binding.comServiceTypeDetail.getEditContent());
                if (TextUtils.isEmpty(binding.legalPerson.getText())) {
                    MToast.showToast(getActivity(), "法人代表不能为空");
                    return;
//                } else if (!binding.legalPerson.getText().toString().equals(entity.getLegalPerson())) {
                } else {
                    viewModel.supplierAuthEntity.get().setLegalPerson(binding.legalPerson.getText().toString());
                }

               /* if (TextUtils.isEmpty(binding.comUserTime.getText())) {
                    MToast.showToast(getActivity(), "营业执照有效期不能为空");
                    return;
                }*/

//                if (TextUtils.isEmpty(binding.registeredCapital.getText())) {
//                    MToast.showToast(getActivity(), "注册资本不能为空");
//                    return;
//                } else if (!binding.registeredCapital.getText().toString().equals(entity.getRegisteredCapital())) {
                //} else {
                    viewModel.supplierAuthEntity.get().setRegisteredCapital(binding.registeredCapital.getText().toString());
                //}

                if (TextUtils.isEmpty(binding.createTime.getText())) {
                    MToast.showToast(getActivity(), "成立日期不能为空");
                    return;
//                } else if (!binding.createTime.getText().toString().equals(entity.getEstablishmentDate())) {
                } else {
                    viewModel.supplierAuthEntity.get().setEstablishmentDate(binding.createTime.getText().toString());
                }

                if (TextUtils.isEmpty(binding.comAddress.getText())) {
                    MToast.showToast(getActivity(), "注册地址不能为空");
                    return;
                }
                if (TextUtils.isEmpty(binding.editAddressDetail.getEditContent())) {
                    MToast.showToast(getActivity(), "详细地址不能为空");
                    return;
//                } else if (!binding.editAddressDetail.getText().toString().equals(entity.getCompanyAddress())) {
                } else {
                    viewModel.supplierAuthEntity.get().setCompanyAddress(binding.editAddressDetail.getEditContent());
                }
                if (TextUtils.isEmpty(viewModel.supplierAuthEntity.get().getUserDTO().getIdentityCard())) {
                    MToast.showToast(getActivity(), "身份证号码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(viewModel.supplierAuthEntity.get().getUserDTO().getRealName())) {
                    MToast.showToast(getActivity(), "姓名不能为空");
                    return;
                }
                if ("0".equals(mParam1)) {
                    if (TextUtils.isEmpty(viewModel.supplierAuthEntity.get().getUserDTO().getTelPhone())){
                        MToast.showToast(getActivity(), "手机号不能为空");
                        return;
                    }
                    if (!CheckUtils.isPhoneNumberValid(viewModel.supplierAuthEntity.get().getUserDTO().getTelPhone())){
                        MToast.showToast(getActivity(), "请输入正确的手机号");
                        return;
                    }
                    if (TextUtils.isEmpty(viewModel.supplierAuthEntity.get().getUserDTO().getCode())) {
                        MToast.showToast(getActivity(), "验证码不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(binding.pwd.getText())) {
                        MToast.showToast(getActivity(), "密码不能为空");
                        return;
                    }
                    String password = binding.pwd.getText().toString();
                    //password = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
                    viewModel.supplierAuthEntity.get().getUserDTO().setPassword(password);
                }
//                if (!isCheck && "1".equals(mParam1)) {
//                    MToast.showToast(getActivity(), "请勾选经营帮用户协议");
//                    return;
//                }
                viewModel.supplierAuthEntity.get().setServiceType(viewModel.supplierAuthEntity.get().getServiceCode());
                viewModel.supplierAuthEntity.get().getUserDTO().setUsername(viewModel.supplierAuthEntity.get().getUserDTO().getTelPhone());
                viewModel.supplierAuthEntity.get().getUserDTO().setType(mParam1);
                if (isCheckEnduring) {
                    viewModel.supplierAuthEntity.get().setBusinessTerm("长期");
                }
                if (binding.createTime.getText().toString().contains("-")){
                    String  time = DateUtils.dateTo10Timesstamp13(binding.createTime.getText().toString()) + "";
                    viewModel.supplierAuthEntity.get().setEstablishmentDate(time);
                }else {
                    String  time = DateUtils.dateTo10Timestamp13(binding.createTime.getText().toString()) + "";
                    viewModel.supplierAuthEntity.get().setEstablishmentDate(time);
                }

                if ("1".equals(mParam1)) {
                    String userNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, "");
                    if (!TextUtils.isEmpty(userNo)) {
                        viewModel.supplierAuthEntity.get().getUserDTO().setUserNo(userNo);
                    }
                }
                viewModel.supplierAuthEntity.get().setChannel(1);
                viewModel.commitCompanyAuth();
                break;
            case R.id.add_img:
                pictureSelector(true, 500, 1);
                break;
            case R.id.com_type:
                if (typeList != null) {
                    showTypePop();
                } else {
                    viewModel.getCompanyTypeModel();
                }
                break;
            case R.id.com_service_type:
                if (comTypes.size() != 0) {
                    //showComTypePop();
                    showCompanyTypePop();
                } else {
                    viewModel.getCompanyTypes();
                }
                break;
            case R.id.tv_get_code_btn:
                if (codeValidation()) {
                    viewModel.getCodeModel();
                }

                break;
            case R.id.com_address:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.tv_agreement:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.LICENCE_URL));
                WebActivity.start(getActivity(), RequestCodeE, ARG_PARAM2, isStartTimer);
                break;
            case R.id.tv_agreement2:
                WebActivity.start(getActivity(), Constants.SUPPLIER_URL);
                break;
            case R.id.tv_privacy:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.POLICY_URL));
                WebActivity.start(getActivity());
                break;
            case R.id.iv_check_box:
            case R.id.iv_checked_box:
                setSureBtn(!isChecked);
                break;
            case R.id.tv_company:
                binding.tvCompany.setVisibility(View.GONE);
                binding.etCompany.setVisibility(View.VISIBLE);
                binding.etCompany.requestFocus();
                break;
        }
    }

    private void setSureBtn(boolean isCheck) {
        isChecked = isCheck;
        if (isCheck) {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_on));
            binding.ivCheckedBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_on));
            binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner);
            binding.tvSureBtn.setEnabled(true);
            binding.tvSureBtn.setOnClickListener(this);
        } else {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_off));
            binding.ivCheckedBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_off));
            binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner_40);
            binding.tvSureBtn.setEnabled(false);
            binding.tvSureBtn.setOnClickListener(null);
        }
    }

    //时间选择器
    public void showTimePop() {
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        TimePickerView timePicker = new TimePickerBuilder(getActivity(), (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (date.after(new Date())){
                MToast.showToast(getContext(), "成立日期不能超过当前时间");
                return;
            }
            String format = sdf.format(date);
            viewModel.supplierAuthEntity.get().setEstablishmentDate(date.getTime() + "");
            binding.createTime.setText(format);
        }).setType(new boolean[]{true, true, true, false, false, false}).setRangDate(startDate, Calendar.getInstance()).setDate(Calendar.getInstance()).build();
        timePicker.show();
    }

    public void showTimePop2() {
        TimePickerView timePicker = new TimePickerBuilder(getActivity(), (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);

        }).setType(new boolean[]{true, true, true, false, false, false}).build();
        timePicker.show();
    }

    public void showTimePop3() {
        TimePickerView timePicker = new TimePickerBuilder(getActivity(), (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            viewModel.supplierAuthEntity.get().setEstablishmentDate(format);
            binding.businessTerm.setText(format);
            binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_no_select_item), null, null, null);
            isCheckEnduring = false;
        }).setType(new boolean[]{true, true, true, false, false, false}).build();
        timePicker.show();
    }

    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_LOGIN);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();

                    // viewModel.addMachineInEntity.get().setAreaName(areaName);
                    // viewModel.addMachineInEntity.get().setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                }
                String content = addressEntityList.get(options1).getName()
                        + opt2.get(options1).get(options2).getName()
                        + areaName;
                binding.comAddress.setText(content);
                viewModel.supplierAuthEntity.get().setProvinceNo(addressEntityList.get(options1).getNo());
                viewModel.supplierAuthEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
                viewModel.supplierAuthEntity.get().setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());

                viewModel.supplierAuthEntity.get().setProvinceName(addressEntityList.get(options1).getName());
                viewModel.supplierAuthEntity.get().setCityName(opt2.get(options1).get(options2).getName());
                viewModel.supplierAuthEntity.get().setDistrictName(opt3.get(options1).get(options2).get(options3).getName());
                //  binding.itemTvWorkPlace.setContent(content);

                // viewModel.addMachineInEntity.get().setProvinceName(addressEntityList.get(options1).getName());
                // viewModel.addMachineInEntity.get().setProvinceNo(addressEntityList.get(options1).getNo());
                // viewModel.addMachineInEntity.get().setCityName(opt2.get(options1).get(options2).getName());
                // viewModel.addMachineInEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);//opt3
        cityOption.show();
    }

    private boolean isLoaded = false;

    public void showAddressPop
            (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };


    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    private boolean codeValidation() {
        if (TextUtils.isEmpty(binding.mobile.getText())) {
            MToast.showToast(getActivity(), "手机号码不能为空");
            return false;
        }
        if (!CheckUtils.isMobileNum(binding.mobile.getText().toString())) {
            MToast.showToast(getActivity(), "请输入正确手机格式");
            return false;
        }
        return true;
    }

    public void getCodeSuccess() {
        SimpleCountDownTimer mCountDownTimerUtils = new SimpleCountDownTimer(getActivity(), binding.tvGetCodeBtn, 60000, 1000,false); //倒计时1分钟
        mCountDownTimerUtils.start();
//        viewModel.getCodeModel();
    }


    public void setCompanyTypes(List<PickFilterEntity<List<PickFilterEntity>>> list) {
        comTypes.clear();
        comTypes.addAll(list);
        //showComTypePop();
        showCompanyTypePop();
    }

    //企业服务类型选择器(多选)
    private void showCompanyTypePop() {
        if (comTypes.isEmpty()) return;
        if (window == null) {
            window = new OneAndTwoLevelMultipleChoiceWindow(getContext());
        }
        window.setTitle("经营类型");
        window.setBgView(binding.grayLayout);
        window.setOnResultClick(list1 -> {
            if (list1.size() > 20){
                MToast.showToast(getContext(), "最多选择20个");
                return;
            }
            StringBuilder builderName = new StringBuilder();
            StringBuilder builderCode= new StringBuilder();
            for (PickFilterEntity entity : list1) {
                builderName.append(entity.getName()).append(",");
                builderCode.append(entity.getNo()).append(",");
            }
            comReallyTypes.clear();
            comReallyTypes.addAll(list1);
            binding.comServiceType.setText(builderName.substring(0, builderName.length() - 1));
            viewModel.supplierAuthEntity.get().setServiceTypeName(builderName.substring(0, builderName.length() - 1));
            viewModel.supplierAuthEntity.get().setServiceCode(builderCode.substring(0, builderCode.length() - 1));
        });
        window.setHistory(comTypes, comReallyTypes);
        window.showPopwindow(binding.comServiceType, Gravity.BOTTOM, 0, 0);
    }


    //企业服务类型选择器(单选)
    private void showComTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = comTypes.get(options1).getName();
                binding.comServiceType.setText(content);
                comTypePosition = options1;
                viewModel.supplierAuthEntity.get().setServiceType(comTypes.get(options1).getName());
                viewModel.supplierAuthEntity.get().setServiceCode(comTypes.get(options1).getNo());
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        businessOption.setPicker(comTypes);
        businessOption.setSelectOptions(comTypePosition);
        businessOption.show();
    }

    //企业类型
    public void showTypePop(List<String> datas) {
        if (datas==null)return;
        this.typeList = datas;
        showTypePop();
    }

    private void showTypePop() {
        //条件选择器
        OptionsPickerView typeOption = new SinglePickBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = typeList.get(options1);
                binding.comType.setText(content);
                //viewModel.supplierAuthEntity.get().setCompanyType(options2);
                viewModel.supplierAuthEntity.get().setCompanyType(typeList.get(options1));
                typePosition = options1;
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        typeOption.setPicker(typeList);
        typeOption.setSelectOptions(typePosition);
        typeOption.show();
    }

    //打开相册
    private void openAlbum() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .minimumCompressSize(500)//小于500kb不压缩
                .maxSelectNum(1)// 最大图片选择数量 int
                .compress(true)//压缩
                .cropCompressQuality(70)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    public void removeList() {
        listLicens.clear();
        binding.addImg.setImageResource(R.drawable.sck);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);   //this
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeE:
                    binding.txAgreement.setText("已阅读并同意");
                    binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner);
                    binding.tvSureBtn.setEnabled(true);
                    binding.tvSureBtn.setOnClickListener(this);
                    break;
            }
        }
    }

    // 图片结果回调
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        if (selectList == null) return;
        if (selectList.get(0) == null || TextUtils.isEmpty(selectList.get(0).getRealPath())) return;
        File file = new File(selectList.get(0).getRealPath());
        MLog.d("图片路径：", selectList.get(0).getRealPath());
        if (file.exists()) {
            MLog.d("图片", "存在");
        }
        listLicens.clear();
        listLicens.add(selectList.get(0).getRealPath());
        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.addImg);
//                    viewModel.upLicenseModel2(file); TODO 2021/4/2 产品新增需求将识别接口开放
        viewModel.upLicenseModel(file);


        // 例如 LocalMedia 里面返回三种path
        // 1.media.getRealPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
    }

    public void uploadSuccess(SupplierAuthEntity data) {
        this.entity = data;
        binding.setViewModel(viewModel);
        Glide.with(this).load(entity.getLicenseUrl()).into(binding.addImg);
        viewModel.supplierAuthEntity.get().setUserDTO(viewModel.person.get());
        binding.editAddressDetail.setEditContent("");
        binding.comAddress.setText("");
        if ("长期".equals(entity.getBusinessTerm())) {
            binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.mipmap.btn_checed2), null, null, null);
            isCheckEnduring = true;
            binding.businessTerm.setHint("请选择营业执照有效期");
            binding.businessTerm.setText("");
        } else {
            binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_no_select_item), null, null, null);
            isCheckEnduring = false;
            if (TextUtils.isEmpty(entity.getBusinessTerm())) {
                binding.businessTerm.setHint("请选择营业执照有效期");
                binding.businessTerm.setText("");
            } else {
                binding.businessTerm.setText(entity.getBusinessTerm());
            }
        }
    }


    public void commitCompanyAuthSuccess() {
        binding.nestedscrollview.setVisibility(View.GONE);
        binding.frameContent.setVisibility(View.GONE);
        binding.doneView.setVisibility(View.VISIBLE);
        //未个人实名认证完成企业认证后调用
        if (!SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false)) {
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PERSON_AUTH, true);
            AuthenticationEvent authenticationEvent = new AuthenticationEvent();
            authenticationEvent.setMessageTag(EventConstant.EVENT_USER_AUTHENTICATION);
            EventBus.getDefault().postSticky(authenticationEvent);
            EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_MAIN_INDEX, 0));  //主动通知刷新消息通讯录数据
            //给SharedPreferenceUtil中的REAL_NAME赋值 保存实名认证的状态
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_NAME, viewModel.supplierAuthEntity.get().getUserDTO().getRealName());
            //保存个人认证状态
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ID_CARD, viewModel.supplierAuthEntity.get().getUserDTO().getIdentityCard());
        }
        activity.entSuccess();
    }

    public void getAuthInfo(SupplierAuthEntity entity) {
        if (entity == null) return;
        viewModel.person.get().setRealName(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, ""));
        viewModel.person.get().setIdentityCard(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ID_CARD, ""));
        binding.comServiceType.setText(entity.getServiceType());
        binding.comServiceTypeDetail.getEditText().setText(entity.getCompanyName());
        binding.name.setEnabled(false);
        binding.idCode.setEnabled(false);
        viewModel.person.get().setTelPhone(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
        binding.mobile.setEnabled(false);
        if (isAgain) {//如果是重新认证回填数据
            Glide.with(this).load(entity.getLicenseUrl()).into(binding.addImg);
            viewModel.supplierAuthEntity.set(entity);
            viewModel.supplierAuthEntity.get().setUserDTO(viewModel.person.get());
            binding.editAddressDetail.setEditContent(entity.getCompanyAddress());
            binding.comAddress.setText(entity.getProvinceName() + entity.getCityName() + entity.getDistrictName());
            if ("长期".equals(entity.getBusinessTerm())) {
                binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.mipmap.btn_checed2), null, null, null);
                isCheckEnduring = true;
                binding.businessTerm.setHint("请选择营业执照有效期");
                binding.businessTerm.setText("");
            } else {
                binding.tvChangqi.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_no_select_item), null, null, null);
                isCheckEnduring = false;
                if (TextUtils.isEmpty(entity.getBusinessTerm())) {
                    binding.businessTerm.setHint("请选择营业执照有效期");
                    binding.businessTerm.setText("");
                } else {
                    binding.businessTerm.setText(entity.getBusinessTerm());
                }
            }
        }
        binding.setViewModel(viewModel);
    }
}